import axios, { AxiosInstance, AxiosRequestConfig } from 'axios';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Session } from '/@/utils/storage';
import qs from 'qs';

/*
 * 根据运行环境获取基础请求URL
 */
export const getUrl = (): string => {
    const value: string = import.meta.env.VITE_API_URL as string
    return value == 'getCurrentDomain' ? window.location.protocol + '//' + window.location.host : value
}


// 配置新建一个 axios 实例
const service: AxiosInstance = axios.create({
	baseURL: getUrl(),
	timeout: 50000,
	headers: { 'Content-Type': 'application/json' },
	paramsSerializer: {
		serialize: function (params) {
			return qs.stringify(params, {allowDots: true});
		}
	}
});

// 添加请求拦截器
service.interceptors.request.use(
	(config: AxiosRequestConfig) => {
		// 在发送请求之前做些什么 token
		config.headers['Form-type'] = "admin";
		if (Session.get('token')) {
			config.headers!['Authorization'] = `${Session.get('token')}`;
			// config.headers['Authorization'] = Session.get('token');
			// (<any>config.headers).common['Authorization'] = `${Session.get('token')}`;
		}
		// if (Session.get('token')) {
		// 	config.headers!['Authorization'] = `${Session.get('token')}`;
		// }
		return config;
	},
	(error) => {
		// 对请求错误做些什么
		return Promise.reject(error);
	}
);

// 添加响应拦截器
service.interceptors.response.use(
	(response) => {
		// 对响应数据做点什么
		const res = response.data;
		if (res.code && res.code !== 200) {
			// `token` 过期或者账号已在别处登录
			if (res.code === 410000 || res.code === 410001 || res.code === 410002 || res.code === 410003 || res.code === 410004 || res.code === 410005) {
				ElMessageBox.alert('你已被登出，请重新登录', '提示', {})
				.then(() => {
					window.location.href = '/admin/login'; // 去登录页
				})
				.catch(() => {
					window.location.href = '/admin/login'; // 去登录页
				});
				Session.clear(); // 清除浏览器全部临时缓存
			}else if (res.code === 900000) { //弹窗提示
				ElMessageBox.alert(res.msg, '提示', {})
				.then(() => {})
				.catch(() => {});
			}else if (res.code === 450000||res.code === 450001) {
				ElMessageBox.alert(res.msg?res.msg:'你的账号没有权限', '提示', {})
				.then(() => {
					window.location = '/admin/401';//无权限
				})
				.catch(() => {
					window.location = '/admin/401';//无权限
				});
				
			}else if(res.data){
				if(res.data.adminpath){
					ElMessageBox.confirm(res.msg, '提示', {
						confirmButtonText: '返回',
						cancelButtonText: '取消',
						type: 'warning'
					}).then(() => {
						window.location = res.data.adminpath;
					}).catch(() => {
						window.location = '/admin/401';
					})
				}else{
					ElMessage.error(res.msg || 'Error');
				}
			}else{
				ElMessage.error(res.msg || 'Error');
			}
			return Promise.reject(res?res:response)
			// return Promise.reject(service.interceptors.response);
		} else if (res.code == 200) {
			return res.data;
		} else {
			ElMessageBox.alert(response.data, '接口错误', {})
				.then(() => {})
				.catch(() => {});
			// return res.data;
			console.log(response)
		}
	},
	(error) => {
		// 对响应错误做点什么
		if (error.message.indexOf('timeout') != -1) {
			ElMessage.error('网络超时');
		} else if (error.message == 'Network Error') {
			ElMessage.error('网络连接错误');
		} else {
			if (error.response.data) ElMessage.error(error.response.statusText);
			else ElMessage.error('接口路径找不到');
		}
		return Promise.reject(error);
	}
);

// 导出 axios 实例
export default service;
